package bb.lanxing.model.gpx;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.util.Log;

public class GpxFileOperator {
    private static final long LONG_MASK = 0XFFFFFFFFL;

    public static List<GpxPoint> getFileList(String filePath) {
        List<GpxPoint> gpxPointList = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(filePath)) {
            ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
            while (true) {
                if (fis.read(buffer.array()) != buffer.array().length) break;
                int latitude = buffer.getInt(0);
                if (fis.read(buffer.array()) != buffer.array().length) break;
                int longitude = buffer.getInt(0);
                if (fis.read(buffer.array()) != buffer.array().length) break;
                int altitude = buffer.getInt(0);
                if (fis.read(buffer.array()) != buffer.array().length) break;
                long time_stamp = buffer.getInt(0) & LONG_MASK;
                GpxPoint gpxPoint = new GpxPoint(latitude, longitude, altitude, time_stamp);
                gpxPointList.add(gpxPoint);
            }
        } catch (IOException e) {
            Log.i("getFileList exception reason " + e.getMessage());
            return null;
        }
        return gpxPointList;
    }

    public static void saveGpxList(String filePath, List<GpxPoint> gpxPointList) {
        for (GpxPoint item : gpxPointList) {
            saveGpx(filePath, item);
        }
    }

    public static void saveGpx(String filePath, GpxPoint gpxPoint) {
        try (FileOutputStream fou = new FileOutputStream(filePath, true)) {
            fou.write(intToByteArrayLittleEndian(gpxPoint.getLatitude()));
            fou.write(intToByteArrayLittleEndian(gpxPoint.getLongitude()));
            fou.write(intToByteArrayLittleEndian(gpxPoint.getAltitude()));
            fou.write(longToByteArrayLittleEndian(gpxPoint.getTime_stamp()));
        } catch (IOException e) {
            Log.i("saveGpx exception reason " + e.getMessage());
        }
    }

    /**
     * int转字节数组 小端模式
     */
    public static byte[] intToByteArrayLittleEndian(int x) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) x;
        bytes[1] = (byte) (x >> 8);
        bytes[2] = (byte) (x >> 16);
        bytes[3] = (byte) (x >> 24);
        return bytes;
    }

    /**
     * long 低32位转字节数组 小端模式
     */
    public static byte[] longToByteArrayLittleEndian(long x) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) x;
        bytes[1] = (byte) (x >> 8);
        bytes[2] = (byte) (x >> 16);
        bytes[3] = (byte) (x >> 24);
        return bytes;
    }
}
